import datetime
import json
from collections import OrderedDict

from applications.extensions import db
from applications.models import BookInfo
from flask import Blueprint, request, jsonify
from applications.models.statusMsg import responseMessage

bookInfo_bp = Blueprint('bookInfo', __name__, url_prefix='/bookInfo')

@bookInfo_bp.post('/addBook')
def doAddBook():
    try:
        if request.method == 'POST':
            data = request.form
            author = data['author']
            publisher = data['publisher']
            publish_time = data['publish_time']
            publish_time_dt = datetime.datetime.strptime(publish_time[:-5], '%Y-%m-%dT%H:%M:%S')
            publish_date = publish_time_dt.date()
            book_name = data['book_name']
            book_type = data['book_type']
            isbn = data['isbn']
            price = data['price']

            # 查询是否已存在该书
            existing_book = BookInfo.query.filter_by(author=author, publisher=publisher, publish_time=publish_date,
                                                     book_name=book_name).first()

            if existing_book:
                existing_book.book_stock += 1
                existing_book.book_inlibrary += 1
                db.session.commit()
                return jsonify({'message': 'Successfully added book', 'data': existing_book.to_dict()})
            else:
                new_book = BookInfo(author=author, publisher=publisher, publish_time=publish_date, book_name=book_name,
                                    book_type=book_type, isbn=isbn, price=price, book_stock=1, book_inlibrary=1)
                db.session.add(new_book)
                db.session.commit()
            return json.dumps(responseMessage(status="200", responsemsg="success").__dict__, ensure_ascii=False)
    except BaseException as e:
        print(e)
        return json.dumps(responseMessage(status="200", responsemsg="error").__dict__, ensure_ascii=False)

@bookInfo_bp.post('/updateBookInfo')
def updateBookInfo():
    try:
        if request.method == 'POST':
            results = db.session.query(BookInfo).filter().all()
            for i in results:
                print(i.book_name)
            db.session.commit()
            print(results)
            return "results"
    except BaseException:
        return "rtteo"

@bookInfo_bp.post('/deleteBooks')
def dodeleteBook():
    isbn_list = request.form.getlist('isbnList[]')  # 获取选中的isbn号列表
    if isbn_list:
        # 在bookInfo表中删除对应的图书信息
        for isbn in isbn_list:
            book = BookInfo.query.filter_by(isbn=isbn).first()
            db.session.delete(book)
        db.session.commit()
        return jsonify(success=True)
    else:
        return jsonify(success=False, message='请选择要删除的图书')
@bookInfo_bp.post('/getAllBookInfo')
def getAllBookInfo():
    def user_to_dict(BookInfo):
        return OrderedDict(
            id=BookInfo.id,
            book_name=BookInfo.book_name,
            book_type=BookInfo.book_type,
            author=BookInfo.author,
            publisher=BookInfo.publisher,
            publish_time=BookInfo.publish_time,
            isbn=BookInfo.isbn,
            add_time=BookInfo.add_time,
            borrow_status=BookInfo.borrow_status,
            book_inlibrary=BookInfo.book_inlibrary,
            book_stock=BookInfo.book_stock,
            price=BookInfo.price
        )
    try:
        if request.method == 'POST':
            results =db.session.query(BookInfo).all()
            db.session.commit()
            return jsonify(list(map(user_to_dict, results)))
    except BaseException:
        return json.dumps(responseMessage(status="200", responsemsg="error").__dict__, ensure_ascii=False)






